package services

import (
	"gitee.com/captials-team/ubdframe/src/common/utils"
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"gitee.com/captials-team/ubdframe/src/domain/dto/paginate"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/domain/models"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"gitee.com/captials-team/ubdframe/src/pkg/passwd"
	"go.uber.org/dig"
)

type AdminService struct {
	l        v1log.ILog
	adminDao interfaces.ItfAdminDao
}

func NewAdminService(di *dig.Container, l v1log.ILog, adminDao interfaces.ItfAdminDao) *AdminService {
	ctr := &AdminService{
		l:        l,
		adminDao: adminDao,
	}

	return ctr
}

// ValidatePassword 校验密码是否正确
func (s *AdminService) ValidatePassword(adminId int64, password string) (bool, error) {
	relPass, relSalt, err := s.adminDao.QueryPassword(adminId)
	if err != nil {
		return false, err
	}

	curPass := passwd.GenSaltPasswordByMd5(password, relSalt)

	return curPass == relPass, nil
}

func (s *AdminService) AutoCreateAdmin(nickname string, account string, password string) error {
	salt := utils.RandLetterFigureCode(16)
	_, err := s.adminDao.AddCheckAccount(&models.Admin{
		Id:       0,
		Account:  account,
		Password: passwd.GenSaltPasswordByMd5(password, salt),
		Salt:     salt,
		Nickname: nickname,
		Avatar:   "",
		Email:    "",
		IsRoot:   1,
		Status:   1,
	})
	return err
}

func (s *AdminService) Search(search *dto.SearchAdminParams, pa *paginate.Pager) ([]*models.Admin, *paginate.Pager, error) {
	return s.adminDao.Search(search, pa)
}

func (s *AdminService) ResetStatus(id int64, status int) (int64, error) {
	return s.adminDao.ResetStatus(id, status)
}

func (s *AdminService) ResetPassword(id int64, password string) (int64, error) {
	return s.adminDao.ResetPassword(id, password, false)
}

func (s *AdminService) ResetRootPassword(id int64, password string) (int64, error) {
	return s.adminDao.ResetPassword(id, password, true)
}

func (s *AdminService) UpdateProInfo(id int64, profile *dto.UpdateProfileParams) (int64, error) {
	return s.adminDao.UpdateProInfo(id, &models.Admin{
		Nickname: profile.Nickname,
		Avatar:   profile.Avatar,
		Email:    profile.Email,
		Phone:    profile.Phone,
	})
}
